package com.bjpowernode.seckillweb.controller;

import com.bjpowernode.constant.Constants;
import com.bjpowernode.entity.Goods;
import com.bjpowernode.entity.Orders;
import com.bjpowernode.entity.Users;
import com.bjpowernode.seckillweb.service.GoodsService;
import com.bjpowernode.seckillweb.service.OrderService;
import com.bjpowernode.vo.HttpResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Tag(name = "商品接口", description = "查询商品列表，商品明细，查看秒杀结果等信息")
@Controller
public class GoodsController {
    @Resource
    private GoodsService goodsService;
    @Resource
    private OrderService orderService;

    @GetMapping("/goods/list")
    public ModelAndView queryGoodsList() {
        List<Goods> goodsList = goodsService.queryGoosList();
        ModelAndView mv = new ModelAndView("list");//list表示要路由的页面
        mv.addObject("goodsList", goodsList);//将goodsList返回给页面
        return mv;
    }

    @GetMapping("/goods/{id}")
    public ModelAndView queryGoodsById(@PathVariable("id") Integer id) {
        Goods goods = goodsService.getById(id);
        goods.setRandomName(null);
        ModelAndView mv = new ModelAndView("detail");
        mv.addObject("goods", goods);
        mv.addObject("nowTime", System.currentTimeMillis());
        return mv;
    }

    @GetMapping("/goods/time/{id}")
    @ResponseBody
    public HttpResult goodsTime(@PathVariable Integer id, HttpServletRequest request) {
        Users user = Users.builder().id(1001).name("jack").build();
        request.getSession().setAttribute(Constants.LOGIN_USER, user);
        Goods goods = goodsService.getById(id);
        HttpResult result = SeckillTimeValidator.validateSeckillTime(goods.getStartTime(), goods.getEndTime());
        return result != null
                ? result
                : HttpResult.builder()
                .code(Constants.SUCCESS)
                .msg("秒杀进行中")
                .data(goods.getRandomName())
                .build();
    }

    @Operation(summary = "查询秒杀结果")
    @GetMapping("/goods/result/{id}")
    @ResponseBody
    public HttpResult queryResult(@PathVariable("id") Integer goodsId, HttpServletRequest request) {
        Users user = (Users) request.getSession().getAttribute(Constants.LOGIN_USER);
        Orders orders = orderService.queryResult(user.getId(), goodsId);
        if (orders != null)
            return HttpResult.builder().code(Constants.SUCCESS).data("秒杀成功").build();
        return HttpResult.builder().code(Constants.ERROR).msg("秒杀进行中").build();
    }
}